package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.dto.CustomerFundDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by DK on 16/11/20.
 */
@Repository
public class CustomerFundRepositoryImpl implements CustomerFundRepositoryCustom{

    private static final Logger log = LoggerFactory.getLogger(CustomerFundRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult<CustomerFundDto> findMallCustomerFundPage(Long customerId, String nickName, String mobile, Long mallId, PageResult pageResult) {
        SQLPageDoing<CustomerFundDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from customer_fund cf left join customer c on cf.customer_id = c.id where 1=1");
            if (customerId != null) {
                sql.append(" and cf.customer_id = :customerId");
                params.put("customerId", customerId);
            }

            if (StringUtils.isNotBlank(nickName)) {
                sql.append(" and c.nick_name = :nickName");
                params.put("nickName", nickName);
            }

            if (StringUtils.isNotBlank(mobile)) {
                sql.append(" and c.mobile = :mobile");
                params.put("mobile", mobile);
            }
            sql.append(" and c.mall_id = :mallId");
            params.put("mallId", mallId);
            sql.append(" order by c.date_created desc");
            fields.append("cf.*, c.nick_name, c.mobile");
        };
        return doing.go(pageResult, CustomerFundDto.class, objectMapper, jdbcTemplate, log);
    }
}
